<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form ref="listQuery" :model="listQuery" inline>
                <el-form-item label="时间范围" prop="filterTime">
                    <el-date-picker size="small" clearable @change="setFilterTime" v-model="listQuery.filterTime" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
                    <el-button size="small" class="filter-item" type="danger" icon="el-icon" @click="resetFilter" style="display: none;">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div style="height: 42px;line-height: 32px;">
            <el-button type="primary" icon="document" @click="handleDownload" :loading="downloadLoading" style="float: right;">下载报表</el-button>
        </div>
        <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%" stripe>
            <el-table-column width="80px" align="center" type="index" label="序号"></el-table-column>
            <el-table-column align="center" :label="item" v-for="(item, index) in tableCols" :key="item">
                <template slot-scope="scope">
                    <span>{{scope.row[index]}}</span>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[20,50,100]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next" :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { reportDailyWork } from '@/api/report'
  import { parseTime, formatSearchTime } from '@/utils'
  import exportExcel from '@/components/Excel/exportExcel'

  // 列表字段：时间（年月日）、分组、衣物合计、缝补合计
  export default {
    name: 'ReportDayWork',
    data() {
      return {
        tableKey: 0,
        list: [],
        tableCols: [],
        total: null,
        listLoading: false,
        listQuery: {
          page: 1,
          size: 20,
          startTime: parseTime(new Date(new Date().getTime() - 31 * 24 * 60 * 60 * 1000 - 1000), '{y}-{m}-{d}'),
          endTime: parseTime(new Date(), '{y}-{m}-{d}'),
          filterTime: [parseTime(new Date(new Date().getTime() - 31 * 24 * 60 * 60 * 1000 - 1000), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')]
        },
        downloadLoading: false
      }
    },
    components: {
      exportExcel
    },
    computed: {
      ...mapGetters([
        'fid'
      ])
    },
    created: function() {
      this.getList()
    },
    filters: {
      parseTime
    },
    methods: {
      getList() {
        if (!this.listQuery.startTime || !this.listQuery.endTime) {
          this.$message({ message: '请先选择查询起止时间', type: 'error', showClose: true })
          return
        }
        this.listLoading = true
        var query = {
          page: this.listQuery.page,
          size: this.listQuery.size,
          startTime: this.listQuery.startTime ? formatSearchTime(this.listQuery.startTime + ' ', true) : '',
          endTime: this.listQuery.endTime ? formatSearchTime(this.listQuery.endTime + ' ') : ''
        }
        reportDailyWork(query).then(response => {
          this.list = response.data && response.data.list || []
          this.tableCols = this.list && this.list.shift(0)
          this.total = Number.parseInt(response.data.count)
          this.listLoading = false
        }).catch(e => {
          this.listLoading = false
        })
      },
      setFilterTime() {
        if (this.listQuery.filterTime && this.listQuery.filterTime.length) {
          var max_date_range = 31 * 24 * 60 * 60 * 1000 - 1000
          if (new Date(this.listQuery.filterTime[1]) - new Date(this.listQuery.filterTime[0]) > max_date_range) {
            this.$message({ message: '时间跨度不能超过一个月', type: 'error', showClose: true })
            var end = new Date(new Date(this.listQuery.filterTime[0]).getTime() + max_date_range)
            this.listQuery.filterTime[1] = parseTime(end, '{y}-{m}-{d}')
          }
          this.listQuery.startTime = this.listQuery.filterTime[0]
          this.listQuery.endTime = this.listQuery.filterTime[1]
          return
        }
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetFilter() {
        this.$refs['listQuery'].resetFields()
        this.setFilterTime()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      handleDownload() {
        if (!this.listQuery.startTime || !this.listQuery.endTime) {
          this.$message({ message: '请先选择查询起止时间', type: 'error', showClose: true })
          return
        }
        this.downloadLoading = true
        var query = {
          page: 1,
          size: 1000,
          startTime: this.listQuery.startTime ? formatSearchTime(this.listQuery.startTime + ' ', true) : '',
          endTime: this.listQuery.endTime ? formatSearchTime(this.listQuery.endTime + ' ') : ''
        }
        reportDailyWork(query).then(response => {
          var excelList = response.data && response.data.list || []
          var tHeader = excelList && excelList.shift(0)
          if (!excelList || !excelList.length) {
            this.$message({ message: '没有可下载的报表', type: 'error', showClose: true })
            this.downloadLoading = false
            return
          }
          import('@/vendor/Export2Excel').then(excel => {
            const data = this.formatJson(tHeader, excelList)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '日工作量统计表' + parseTime(query.startTime, '{y}-{m}-{d}') + '至' + parseTime(query.endTime, '{y}-{m}-{d}'),
              autoWidth: true
            })
            this.downloadLoading = false
          })
        }).catch(e => {
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map((j, i) => {
          return v[i]
        }))
      }
    }
  }
</script>

<style scoped>
    .el-range-editor.el-input__inner {
        width: 273px;
        padding: 3px;
    }
</style>